import {designPage, onMounted, watch} from "@peryl/react-compose";
import {AppRouter} from "../AppRouter";
import {Alert, Scroll} from "plain-design";
import {$useCmsRunningOption, $useRunningOption, eRenderDirection, provideCmsRunningOption, RenderList} from "../../packages";
import {DefaultRunningConfig} from "../module/cms-visual-editor";
import {createEffects} from "@peryl/utils/createEffects";
import {env} from "../env";

export default designPage(() => {

  const filePath = AppRouter.state.route.query?.path;

  if (!filePath) {
    return <Alert label="Missing require query param: path" status="error"/>;
  }

  const runningOption = $useRunningOption({ ...DefaultRunningConfig, isRunning: true });

  const cmsRunningOption = $useCmsRunningOption({
    runningOption: runningOption,
    effects: createEffects().effects,
    config: {
      isRunning: true,
      assetsPrefix: env.assetsPrefix,
      runningOptionConfig: DefaultRunningConfig,
      getSnapshot: {} as any,
      editorOptionConfig: {} as any,
    },
  });
  // !!props.dataMetas && cmsRunningOption.state.updateStateData(props.dataMetas);

  provideCmsRunningOption(cmsRunningOption);

  // watch(() => props.dataMetas, val => {cmsRunningOption.state.updateStateData(val ?? []);});

  onMounted(async () => {
    const resp = await fetch(filePath);
    const data = await resp.json();
    cmsRunningOption.state.updateStateData(data);
  });

  const onReachBottom = () => cmsRunningOption.hooks.onReachBottom.exec(undefined);

  return () => (
    <div style={{ height: '100vh', width: '100vw' }}>
      <Scroll onVerticalScrollBottom={onReachBottom}>
        <RenderList direction={eRenderDirection.vertical}/>
      </Scroll>
    </div>
  );
});
